/**
 * 全站权限配置
 * 
 */
import {store} from './store'
import NProgress from 'nprogress' // progress bar

export default {
  beforeEach:async (to, from, next) => {
    if(to.query.token){
      // 1.获取token值，并写入
      // 2.隐藏边框操作
      store.commit('organization/user/SET_TOKEN', to.query.token)
    }


    const tagWel = store.getters.tagWel
    

    store.commit('SET_TAG_LOADING', true)

    const meta = to.meta || {}

    if (store.getters.token) {
      const value = to.query.src || to.path//to.fullPath;
      
      if(['/login','/404','/403','/500'].includes(value)){
        next()
        return;
      }

      
      if(store.state.app.system.online && (store.getters.project == null || store.getters.project.f_Id != '030ecf98-cc3a-4ed3-8186-f3de8706a4e5')){
        const api = window.$api.codetool.project
        const data = await window.$awaitWraper(api.getList())
        store.dispatch("codetool/project/set",data[0])
      }

      if(store.state.app.isFirstLoad){
        // 加载登录者信息
        await store.dispatch('organization/user/getLoginInfo')
        // 加载菜单信息
        await store.dispatch("system/module/getList")
        // 加载动态桌面
        if(store.getters.appConfig.isDynamicHome){
          const dynamicHomes = store.state.system.module.list.filter(t=>{
            if(t.f_Target == 'desktop1'){
              if(store.getters.loginInfo.f_SecurityLevel == 1){
                return true
              }
              else{
                const moduleAuthIds = store.getters.loginInfo.moduleAuthIds || []
                if(moduleAuthIds.indexOf(t.f_ModuleId) > -1){
                  return true
                }
              }
            }
            return false
          })

          if(dynamicHomes.length > 0){
            // 设置首页
            store.commit('SET_TAG_DYNAMICHOME',dynamicHomes[0])
            dynamicHomes.forEach(t=>{
              store.commit('ADD_TAG', {
                label: t.f_FullName,
                value: t.f_UrlAddress,
                params: {routerPath: "module"},
                query: {
                  close: "false",
                  name: t.f_FullName,
                  src: t.f_UrlAddress,
                  target: "desktop1"
                },
                meta: {},
              })
            })
          }
          else{
            store.commit('SET_TAG_DYNAMICHOME',undefined)
          }
        }
        store.commit('app/SET_ISFIRSTLOAD',false)
      }

      // 获取当前路由在模块中是否存在
      const modules = store.state.system.module.list
      const currentModlue = modules.find(t=>t.f_UrlAddress == value && t.f_EnabledMark == 1)


      // 进行路由拦截，跳转到动态桌面
      if((value == tagWel.value || value == 'learun_desktop_nosetting' )  && store.getters.appConfig.isDynamicHome){
        if(store.getters.tagDynamicHome && modules.findIndex(t=>t.f_UrlAddress == store.getters.tagDynamicHome.f_UrlAddress && t.f_EnabledMark == 1) != -1){
          window.$router.$lrRouter.goto(store.getters.tagDynamicHome)
          return
        }
        else if(value == tagWel.value){
          store.commit('SET_TAG_DYNAMICHOME',null)
          window.$router.$lrRouter.goto({
            f_FullName: "空桌面",
            f_SortCode: 0,
            f_Target: "desktop1",
            f_UrlAddress: "learun_desktop_nosetting",
          })//在没有配置首页配置的情况下跳转到一个特定的默认页面
          return
        }
      }


  
      if(currentModlue == undefined && value != tagWel.value && !meta.isNotMenu && value != 'learun_desktop_nosetting'){
        next({ path: '/404' })
        return
      }

      // 判断当前路由是否在权限里
      const loginInfo = store.state.organization.user.loginInfo
      const moduleAuthIds = loginInfo.moduleAuthIds || []
  
      
      if(value != tagWel.value && value != 'learun_desktop_nosetting' && loginInfo.f_SecurityLevel != 1 && !meta.isNotMenu && !moduleAuthIds.includes(currentModlue.f_ModuleId)){
        next({ path: '/403' })
        return
      }

      let label = to.query.name || meta.name || to.name 
      if(currentModlue){
        label = currentModlue.f_FullName
      }
      if( tagWel.value == value){
        label = tagWel.label
      }
      
      if (meta.isTab !== false && !window.$validatenull(value) && !window.$validatenull(label)) {
        store.commit('ADD_TAG', {
          label: label,
          value: value,
          params: to.params,
          query: to.query,
          meta: meta,
        })
      }

      next()
      
    } else {
      //判断是否需要认证，没有登录访问去登录页
      if (meta.isAuth === false) {
        next()
      } else {
        next('/login')
      }
    }
  },
  
  afterEach:(to) => {
    NProgress.done()
    let title = to.name //store.getters.tag.label
    title = window.$router.$lrRouter.generateTitle(title)
    //根据当前的标签也获取label的值动态设置浏览器标题

    const modules = store.state.system.module.list
    const value = to.query.src || to.path//to.fullPath;
    const currentModlue = modules.find(t=>t.f_UrlAddress ==value && t.f_EnabledMark == 1)

    const tagWel = store.getters.tagWel
    if(tagWel.value == value || value == 'learun_desktop_nosetting'){
      title = tagWel.label
    }
    if(currentModlue){
      title = currentModlue.f_FullName
    }


    store.commit('SET_TAG_LOADING', false)

    window.$router.$lrRouter.setTitle(title)

    // 提交访问日志
    if(!['/login','/404','/403','/500'].includes(value)){
      window.$api.system.log.visit({moduleName:title,moduleUrl:value})
    }
  },
  
  onError:(err) => {
    //const pattern = /Loading chunk (\d)+ failed/g;
    //const isChunkLoadFailed = error.message.match(pattern);
    const targetPath = window.$router.history.pending.fullPath;
    // 因为webpack插件的bug导致打包的后的js丢失，没有太好的解决方法，目前做的是记录信息，重新打包解决
    console.error(err,targetPath)
    if(targetPath != '/404'){
      window.$router.push({ path: '/404' })
    }
    
  }
}


